package com.zone.core.binding

import android.graphics.drawable.Drawable
import android.widget.ImageView
import androidx.databinding.BindingAdapter
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target

/**
 *Author: last
 *Time: 2020-09-02
 *Description: ImageView 适配器
 */
@BindingAdapter("android:src")
fun setImage(imageView: ImageView, imgRes: Int) {
    imageView.setImageResource(imgRes)
}
@BindingAdapter("android:src")
fun setImage(imageView: ImageView, drawable: Drawable?) {
    imageView.setImageDrawable(drawable)
}

@BindingAdapter("imageUrl")
fun loadImage(imageView: ImageView, url: String?) {
    Glide.with(imageView.context)
        .load(url)
        .into(imageView)
}

@BindingAdapter("originImageUrl")
fun loadOriginImage(imageView: ImageView, url: String?) {
    Glide.with(imageView.context)
        .load(url)
        .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
        .into(imageView)
}

@BindingAdapter("imageUrl", "round")
fun loadImage(imageView: ImageView, url: String?, round: Float) {
    Glide.with(imageView.context)
        .load(url)
        .transform(CenterCrop(), RoundedCorners(round.toInt()))
        .into(imageView)
}

@BindingAdapter("imageUrl", "round", "placeHolder")
fun loadImage(imageView: ImageView, url: String?, round: Float, holderDrawable: Drawable) {
    Glide.with(imageView.context)
        .load(url)
        .placeholder(holderDrawable)
        .transform(CenterCrop(), RoundedCorners(round.toInt()))
        .into(imageView)
}

@BindingAdapter("imageUrl", "round", "placeHolder", "imageSize")
fun loadImage(imageView: ImageView, url: String?, round: Float, holderDrawable: Drawable, size : Float) {
    Glide.with(imageView.context)
        .load(url)
        .placeholder(holderDrawable)
        .override(size.toInt(), size.toInt())
        .transform(CenterCrop(), RoundedCorners(round.toInt()))
        .into(imageView)
}

@BindingAdapter("imageUrl", "placeHolder", "error")
fun loadImage(
    imageView: ImageView,
    url: String?,
    holderDrawable: Drawable,
    errorDrawable: Drawable
) {
    Glide.with(imageView.context)
        .load(url)
        .placeholder(holderDrawable)
        .apply(RequestOptions().error(errorDrawable))
        .into(imageView)
}

@BindingAdapter("imageUrl", "error")
fun loadImageError(imageView: ImageView, url: String?, errorDrawable: Drawable) {
    Glide.with(imageView.context)
        .load(url)
        .apply(RequestOptions().error(errorDrawable))
        .into(imageView)
}

@BindingAdapter("imageUrl", "placeHolder")
fun loadImage(imageView: ImageView, url: String?, holderDrawable: Drawable) {
    Glide.with(imageView.context)
        .load(url)
        .placeholder(holderDrawable)
        .into(imageView)
}